<?php
declare (strict_types = 1);

namespace app\controller;

use app\model\Area as AreaModel;

use app\BaseController;
use Exception;
use think\App;
use think\facade\Cache;
use think\Response;

class Area extends BaseController
{
    private  AreaModel $model;

    /**
     * 地区列表的树形数据 缓存key
     */
    public const AREA_TREE_LIST_CACHE_KEY = 'AreaTreeListCacheKey';

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new AreaModel();
    }

    /**
     * 显示资源列表
     *
     * @return Response
     */
    public function list(): Response
    {

        $fields = 'id as value,cname as label,parent_id,ctype';
        $where = [
            ['ctype', '>', 0]
        ];
        $data = Cache::get(self::AREA_TREE_LIST_CACHE_KEY);
        if (!empty($data)) {
            return $this->success('success' , $data);
        }

        try {
            $list = $this->model->field($fields)->where($where)->select()->toArray();
            $data = buildTree($list, 1);
            Cache::set(self::AREA_TREE_LIST_CACHE_KEY, $data);
            return $this->success('success' , $data);
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}
